package nowcoder.offer;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 和为S的连续正数序列
 *
 * @author briarbear
 * @blog https://briarbear.github.io
 * @date 2018-08-28 12:10
 */
public class FindContinuousSequence {

    public ArrayList<ArrayList<Integer>> solution(int sum){
        int len = 2;
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        //从1开始
        while ((sum / len >= len/2)){

            //len为奇数
            if (len % 2 != 0){
                int avg  = sum / len;  //均数
                if (avg * len == sum){
                    int start = avg - (len-1)/2;
                    int end = avg + (len-1)/2;
                    if (start<=0){
                        len++;
                        continue;
                    }
                    ArrayList<Integer> list = new ArrayList<>();
                    for (int i = start; i <= end; i++) {
                        list.add(i);
                    }
                    res.add(list);
                }

            }else {
            //len为偶数
                int avg = sum / len;
                if (sum % len !=0 && (avg + 0.5) * len - sum ==0){
                    int start = avg - (len/2-1);
                    int end = avg + len/2;
                    ArrayList<Integer> list = new ArrayList<>();
                    for (int i = start; i <= end; i++) {
                        list.add(i);
                    }
                    res.add(list);
                }
            }
            len++;

        }

        Collections.reverse(res);
        return res;
    }

    public static void main(String[] args) {
        ArrayList<ArrayList<Integer>> res = new FindContinuousSequence().solution(15);
        res.forEach(o -> System.out.print(o + " "));
    }
}
